package com.walkline.screen;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import net.rim.blackberry.api.browser.Browser;
import net.rim.blackberry.api.browser.BrowserSession;
import net.rim.device.api.browser.field2.BrowserField;
import net.rim.device.api.browser.field2.BrowserFieldConfig;
import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.system.AccelerometerSensor;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.ScrollView;
import net.rim.device.api.ui.TransitionContext;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.util.StringProvider;

import com.walkline.moment.MomentSDK;
import com.walkline.moment.inf.StoryDetails;
import com.walkline.util.Enumerations.RefreshActions;
import com.walkline.util.Function;
import com.walkline.util.ui.MyKeyListener;
import com.walkline.util.ui.MyShakeListener;
import com.walkline.util.ui.MyShakeListener.OnShakeListener;

public class StoryDetailsScreen extends MainScreen implements OnShakeListener
{
	MomentSDK _moment;
	String _url;
	LabelField _title;
	StoryDetails _storyDetail;
	BrowserField _browserField;
	VerticalFieldManager _vfm = new VerticalFieldManager(ScrollView.VERTICAL_SCROLL);
	boolean _night_mode = false;

	MyShakeListener _shakeListener = null;

	int _targetWidth = Display.getWidth();
	int _targetHeight = _targetWidth /2;

	public StoryDetailsScreen(MomentSDK moment, String url)
	{
		super(MainScreen.VERTICAL_SCROLL | MainScreen.VERTICAL_SCROLLBAR | NO_SYSTEM_MENU_ITEMS);

		_moment = moment;
		_url = url;

		BrowserFieldConfig config = new BrowserFieldConfig();
		config.setProperty(BrowserFieldConfig.NAVIGATION_MODE, BrowserFieldConfig.NAVIGATION_MODE_POINTER);
		_browserField = new BrowserField(config);

		MyKeyListener listener = new MyKeyListener(_vfm);
		addKeyListener(listener);

		_vfm.add(_browserField);
		add(_vfm);

		Function.attachTransition(this, TransitionContext.TRANSITION_SLIDE);

		if (AccelerometerSensor.isSupported())
		{
			_shakeListener = new MyShakeListener();
			_shakeListener.setOnShakeListener(this);
		}

		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run()
			{
				RefreshStoriesScreen popupScreen = new RefreshStoriesScreen(_moment, _url, RefreshActions.STORYDETAILS);
				UiApplication.getUiApplication().pushModalScreen(popupScreen);

				_storyDetail = popupScreen.getStoryDetails();

				if (popupScreen != null) {popupScreen = null;}
				if (_storyDetail != null) {refreshUI();}
			}
		});
	}

	private void refreshUI()
	{
		String html = _storyDetail.getHTMLBody();

		try {
			InputStream input = getClass().getResourceAsStream("/css/main");
			String css = new String(IOUtilities.streamToBytes(input));

			_browserField.displayContent("<html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width, minimum-scale=1.0, maximum-scale=1.0'>" + css + "</head><body><div id='night' class=''>" + new String(html.getBytes("utf-8")) + "</div></body></html>", "localhost://");
		} catch (UnsupportedEncodingException e) {}
		  catch (IOException e) {}
	}

	private void browseInBrowser()
	{
		BrowserSession session = Browser.getDefaultSession();
		session.displayPage(_storyDetail.getShareUrl());
	}

	MenuItem menuBrowseInBrowser = new MenuItem(new StringProvider("查看原文"), 100, 10)
	{
		public void run() {browseInBrowser();}
	};

	MenuItem menuNightMode = new MenuItem(new StringProvider("夜间模式"), 100, 20)
	{
		public void run()
		{
			String className;
			String jsCode;

			_night_mode = !_night_mode;

			if (_night_mode)
			{
				menuNightMode.setText(new StringProvider("\u221A夜间模式"));
				className = "night";
			} else {
				menuNightMode.setText(new StringProvider("夜间模式"));
				className = "";
			}

			jsCode = "var obj=document.getElementById('night');obj.className='" + className + "'";
			try {_browserField.executeScript(jsCode);} catch (Exception e) {}
		}
	};

	protected void makeMenu(Menu menu, int instance)
	{
		menu.add(menuBrowseInBrowser);
		menu.add(menuNightMode);
		menu.addSeparator();

		super.makeMenu(menu, instance);
	};

	public boolean onClose()
	{
		if (_shakeListener != null) {_shakeListener.stop();}
		UiApplication.getUiApplication().popScreen(this);

		return true;
	}

	public void onShake()
	{
		//Function.errorDialog("SHAKED!!!!!!");
		String className;
		String jsCode;

		_night_mode = !_night_mode;

		if (_night_mode)
		{
			menuNightMode.setText(new StringProvider("\u221A夜间模式"));
			className = "night";
		} else {
			menuNightMode.setText(new StringProvider("夜间模式"));
			className = "";
		}

		jsCode = "var obj=document.getElementById('night');obj.className='" + className + "'";
		try {_browserField.executeScript(jsCode);} catch (Exception e) {}
	}
}